﻿using GGetTestService.Entity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace GGetTestService.MyDbContext
{
    public class SqlServerDbContext : DbContext
    {
        private readonly IWebHostEnvironment _env;

        /// <summary>
        /// 必须写此构造函数，否则在Startup中注入上下文无效
        /// </summary>
        /// <param name="env"></param>
        /// <param name="options"></param>
        public SqlServerDbContext(IWebHostEnvironment env, DbContextOptions<SqlServerDbContext> options) : base(options)
        {
            _env = env;
        }
        public DbSet<Student> Students { get; set; }

        public DbSet<Teacher> Teachers { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            #region 本地调试打开sql日志
            if (_env.IsDevelopment())
            {
                var loggerFactory = new LoggerFactory();
                loggerFactory.AddProvider(new EFLoggerProvider());
                optionsBuilder.EnableSensitiveDataLogging(true);
                optionsBuilder.UseLoggerFactory(loggerFactory);
            }
            #endregion 本地调试打开sql日志

            //optionsBuilder.UseSqlServer($"Server=.;Database=GGetTest;Integrated Security=True");
        }

        public override void Dispose()
        {
            //System.Console.WriteLine($"SqlServerDbContext中的Dispose执行了");
        }
    }
}
